package NIO;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}15:39
 */

//使用NIO完成网络通信的三个核心
    /*
    * 通道：复制链接
    *
    * 缓存区：复制数据的存取
    *
    * 选择器：是SelectableChannel 的多路复用。用于监控SelectableChannel 的IO情况
    * */
public class TestBlockingNIO {
    //客户端
    @Test
    public void client() throws IOException {
        //获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));

        FileChannel inChannel = FileChannel.open(Paths.get("C:\\Users\\VX5\\Desktop\\图片1.png"), StandardOpenOption.READ);
        //分配指定大小的缓存区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //读取本地文件，并发送到服务端
        while (inChannel.read(buffer) != -1){
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
        inChannel.close();
        socketChannel.close();
    }

    //服务端
    @Test
    public void server() throws IOException {
        //获取通道
        ServerSocketChannel ssChannel = ServerSocketChannel.open();

        FileChannel outChannel = FileChannel.open(Paths.get("C:\\Users\\VX5\\Desktop\\图片2.png"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);

        //绑定连接
        ssChannel.bind(new InetSocketAddress(9898));

        //获取客户端连接的通道
        SocketChannel accept = ssChannel.accept();

        //分配一个指定大小的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //接受客户端的数据，保存到本地
        while (accept.read(buffer) != -1){
            buffer.flip();
            outChannel.write(buffer);
            buffer.clear();
        }

        //关闭对应的通道
        accept.close();
        outChannel.close();
        ssChannel.close();
    }
}
